<template>
  <div style="padding: 10px">
    <!-- 操作按钮区域 -->
    <div>
      <div style="margin: 10px 0">
        <el-button @click="add">新增</el-button>
      </div>
      <!-- 搜索区域 -->
      <div style="margin: 10px 0">
        <el-input
            v-model="queryParams.search"
            clearable
            placeholder="请输入内容"
            style="width: 20%"
        />
        <el-button style="margin-left: 5px" type="primary" @click="load">
          查询
        </el-button>
      </div>
    </div>
    <!-- 表格区域 -->
    <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%"
        v-loading="tableLoading"
        @selection-change="handleSelectionChange"
    >

      <el-table-column type="selection" width="55"/>
      <el-table-column label="用户名" prop="username"/>
      <el-table-column label="全名" prop="fullName"/>
      <el-table-column label="年龄" prop="age" width="60"/>
      <el-table-column label="地址" prop="address"/>
      <el-table-column label="性别" prop="gender"/>
      <el-table-column fixed="right" label="操作">
        <template #default="scope">
          <el-button link type="primary" @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-popconfirm
              :icon="InfoFilled"
              icon-color="#626AEF"
              title="你确定删除吗?"
              width="220"
              @confirm="handleDelete(scope.row)"
          >
            <template #reference>
              <el-button type="text">删除</el-button>
            </template>
          </el-popconfirm>
          <el-button type="warning" @click="setRoleById(scope.row)">设为管理员</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <div style="margin: 10px 0; text-align: right">
      <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :background="true"
          :page-sizes="[5, 10, 20, 30]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
      <el-button type="danger" :disabled="multipleSelection.length === 0" @click="batchDelete">删除</el-button>
    </div>
    <!-- 弹窗区域 -->
    <el-dialog v-model="dialogVisible" title="用户操作" width="500">
      <el-form :model="form" label-width="120px">
        <el-form-item label="用户名">
          <el-input v-model="form.username" style="width: 80%"/>
        </el-form-item>
        <el-form-item label="全名">
          <el-input v-model="form.fullName" style="width: 80%"/>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="form.age" style="width: 80%"/>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="form.phone" style="width: 80%"/>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="form.gender">
            <el-radio label=0>男</el-radio>
            <el-radio label=1>女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="地址">
          <el-input
              v-model="form.address"
              style="width: 80%"
              type="textarea"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>


<script>
import {
  addUserAPI,
  deleteUserAPI,
  updateUserAPI,
  getUserPageListAPI, getUserList, getUserListByType, updateUserInfo, batchDelete, setRoleById, addUser,
} from "@/api/user";

export default {
  name: "CommonUser",
  data() {
    return {
      form: {}, // 表单数据
      dialogVisible: false, // 弹窗显示状态
      multipleSelection: [],
      deleteList: [],
      queryParams: {
        // 查询参数
        type: 2,
        pageNum: 1,
        pageSize: 10,
      },
      pageSizes: [5, 10, 20, 30], // 分页每页显示条数选项
      total: 0, // 数据总数
      tableLoading: false, // 表格加载状态
      tableData: [], // 表格数据

    };
  },
  created() {
    this.load(); // 页面加载时获取数据
  },
  methods: {
    batchDelete() {
      batchDelete(this.deleteList).then(res => {
        this.load()
      })
    }, setRoleById(scope) {
      const param = {userId: Number(scope.id)}
      setRoleById(param).then(res => {
        this.load()
      })
    },
    // 加载表格数据
    load() {
      this.tableLoading = true;
      getUserListByType(this.queryParams)
          .then((res) => {
            if (res.code === 200) {
              res.data.list.forEach((item) => {
                item.gender = item.gender === 0 ? "男" : "女";
              });
              this.tableData = res.data.list;
              this.total = res.data.totalCount;
            }
          })
          .finally(() => {
            this.tableLoading = false;
          });
    },
    // 打开新增弹窗
    add() {
      this.dialogVisible = true;
      this.form = {}; // 清空表单数据
    },
    handleSelectionChange(selection) {
      this.multipleSelection = selection;
      this.deleteList = selection.map(v => Number(v.id));
    },
    // 保存操作（新增或更新）
    save() {
      console.log('Saving form:', this.form); // 添加日志
      if (this.form.id) {
        this.form.password = null
        // 更新操作
        updateUserInfo(this.form).then((res) => {

          this.$message.success("更新成功");
          this.dialogVisible = false; // 关闭弹窗
          this.load(); // 刷新表格数据
        });
      } else {
        this.form.type = 2
        this.form.gender = Number(this.form.gender)
        // 新增操作
        addUser(this.form).then((res) => {
          this.$message.success("新增成功");
          this.dialogVisible = false; // 关闭弹窗
          this.load(); // 刷新表格数据
        });
      }
    },
    // 编辑操作
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row)); // 深拷贝行数据到表单
      this.dialogVisible = true;
    },
    // 删除操作
    handleDelete(row) {
      deleteUserAPI(row.id).then((res) => {
        this.$message.success("删除成功");
        this.load(); // 刷新表格数据
      });
    },
    // 分页每页显示条数改变时触发
    handleSizeChange(pageSize) {
      this.queryParams.pageSize = pageSize;
      this.load();
    },
    // 分页当前页码改变时触发
    handleCurrentChange(pageNum) {
      this.queryParams.pageNum = pageNum;
      this.load();
    },
  },
};
</script>